/**
 * 配送模块配置文件
 * 基于JH项目的wms-config.js格式，集中管理所有明道云工作表的字段ID
 * 支持从 mdye.env.config 读取运行时参数，实现参数化配置
 */

/**
 * 从 mdye.env.config 读取配置参数
 * @param {string|Array} ids - 变量ID或ID数组，支持多别名
 * @param {any} fallback - 默认值
 * @returns {any} 配置值或默认值
 */
function readEnv(ids, fallback = '') {
  // 确保ids是数组格式
  const idList = Array.isArray(ids) ? ids : [ids];
  
  // 定义可能的注入位置（支持不同宿主环境）
  const hosts = [window, window.parent, window.top].filter(Boolean);
  
  // 定义可能的配置对象路径
  const configPaths = [
    'mdye.env.config',
    'mdye.env', 
    'env'
  ];
  
  // 遍历所有可能的配置源
  for (const host of hosts) {
    for (const path of configPaths) {
      try {
        const config = path.split('.').reduce((obj, key) => obj?.[key], host);
        if (config && typeof config === 'object') {
          // 尝试所有可能的变量ID
          for (const id of idList) {
            if (config[id] !== undefined && config[id] !== null && config[id] !== '') {
              return config[id];
            }
          }
        }
      } catch (error) {
        // 忽略访问错误，继续尝试下一个路径
        continue;
      }
    }
  }
  
  return fallback;
}

/**
 * 获取配置快照（用于调试）
 * @returns {Object} 配置快照
 */
function getConfigSnapshot() {
  const hosts = [window, window.parent, window.top].filter(Boolean);
  const configPaths = ['mdye.env.config', 'mdye.env', 'env'];
  
  const snapshot = {
    availableKeys: [],
    values: {},
    sources: []
  };
  
  for (const host of hosts) {
    for (const path of configPaths) {
      try {
        const config = path.split('.').reduce((obj, key) => obj?.[key], host);
        if (config && typeof config === 'object') {
          snapshot.availableKeys = [...new Set([...snapshot.availableKeys, ...Object.keys(config)])];
          snapshot.sources.push(`${host === window ? 'window' : host === window.parent ? 'parent' : 'top'}.${path}`);
          
          // 记录关键配置值（敏感信息打码）
          const sensitiveKeys = ['AppKey', 'Sign', 'SecretKey'];
          Object.keys(config).forEach(key => {
            if (sensitiveKeys.includes(key)) {
              snapshot.values[key] = config[key] ? `${config[key].substring(0, 4)}...` : '未配置';
            } else {
              snapshot.values[key] = config[key] || '未配置';
            }
          });
        }
      } catch (error) {
        continue;
      }
    }
  }
  
  return snapshot;
}

// 工作表ID配置 - 使用getter延迟读取，支持运行时参数化
export const WORKSHEET_IDS = {
  get DELIVERY_ORDERS() {
    return readEnv(['DELIVERY_ORDERS', 'deliveryOrders', 'delivery_orders'], '');
  },
  get DELIVERY_SITES() {
    return readEnv(['DELIVERY_SITES', 'deliverySites', 'delivery_sites'], '');
  },
  get CONTAINERS() {
    return readEnv(['CONTAINERS', 'containers'], '');
  },
  get CONTAINER_MANAGEMENT() {
    return readEnv(['CONTAINER_MANAGEMENT', 'containerManagement', 'container_management'], '');
  },
  get DRIVERS() {
    return readEnv(['DRIVERS', 'drivers'], '');
  },
  get VEHICLES() {
    return readEnv(['VEHICLES', 'vehicles'], '');
  }
};

// 视图ID配置 - 使用getter延迟读取
export const VIEW_IDS = {
  get DELIVERY_ORDERS_DEFAULT() {
    return readEnv(['DELIVERY_ORDERS_DEFAULT', 'deliveryOrdersDefault', 'delivery_orders_default'], '');
  },
  get DELIVERY_SITES_DEFAULT() {
    return readEnv(['DELIVERY_SITES_DEFAULT', 'deliverySitesDefault', 'delivery_sites_default'], '');
  },
  get CONTAINERS_DEFAULT() {
    return readEnv(['CONTAINERS_DEFAULT', 'containersDefault', 'containers_default'], '');
  }
};

// API配置 - 使用getter延迟读取，支持运行时参数化
export const API_CONFIG = {
  get baseURL() {
    return readEnv(['apiAddress', 'baseURL', 'api_base_url'], '');
  },
  get userInfoURL() {
    return readEnv(['apiUser', 'userInfoURL', 'api_user_url'], '');
  },
  get appKey() {
    return readEnv(['AppKey', 'appKey', 'app_key'], '');
  },
  get sign() {
    return readEnv(['Sign', 'sign'], '');
  },
  get secretKey() {
    return readEnv(['SecretKey', 'secretKey', 'secret_key'], '');
  },
  get appId() {
    return readEnv(['appId', 'appID', 'APP_ID'], '');
  }
};

// 配送单相关字段 - 使用getter延迟读取
export const DELIVERY_ORDER_FIELDS = {
  get ORDER_NUMBER() {
    return readEnv(['DELIVERY_ORDER_FIELDS.ORDER_NUMBER', 'ORDER_NUMBER', 'orderNumber'], '');
  },
  get METHOD() {
    return readEnv(['DELIVERY_ORDER_FIELDS.METHOD', 'METHOD', 'deliveryMethod'], '');
  },
  get DESTINATION() {
    return readEnv(['DELIVERY_ORDER_FIELDS.DESTINATION', 'DESTINATION', 'destination'], '');
  },
  get DRIVER() {
    return readEnv(['DELIVERY_ORDER_FIELDS.DRIVER', 'DRIVER', 'driver'], '');
  },
  get VEHICLE() {
    return readEnv(['DELIVERY_ORDER_FIELDS.VEHICLE', 'VEHICLE', 'vehicle'], '');
  },
  get CONTAINER() {
    return readEnv(['DELIVERY_ORDER_FIELDS.CONTAINER', 'CONTAINER', 'container'], '');
  },
  get CONTAINER_CODES() {
    return readEnv(['DELIVERY_ORDER_FIELDS.CONTAINER_CODES', 'CONTAINER_CODES', 'containerCodes'], '');
  },
  get REMARKS() {
    return readEnv(['DELIVERY_ORDER_FIELDS.REMARKS', 'REMARKS', 'remarks'], '');
  },
  get STATUS() {
    return readEnv(['DELIVERY_ORDER_FIELDS.STATUS', 'STATUS', 'status'], '');
  },
  get CREATED_AT() {
    return readEnv(['DELIVERY_ORDER_FIELDS.CREATED_AT', 'CREATED_AT', 'createdAt'], '');
  },
  get UPDATED_AT() {
    return readEnv(['DELIVERY_ORDER_FIELDS.UPDATED_AT', 'UPDATED_AT', 'updatedAt'], '');
  },
  get EXPECTED_DELIVERY_TIME() {
    return readEnv(['DELIVERY_ORDER_FIELDS.EXPECTED_DELIVERY_TIME', 'EXPECTED_DELIVERY_TIME', 'expectedDeliveryTime'], '');
  },
  get ACTUAL_DELIVERY_TIME() {
    return readEnv(['DELIVERY_ORDER_FIELDS.ACTUAL_DELIVERY_TIME', 'ACTUAL_DELIVERY_TIME', 'actualDeliveryTime'], '');
  },
  get PHONE_NUMBER() {
    return readEnv(['DELIVERY_ORDER_FIELDS.PHONE_NUMBER', 'PHONE_NUMBER', 'phoneNumber'], '');
  },
  get CONTAINER_COUNT() {
    return readEnv(['DELIVERY_ORDER_FIELDS.CONTAINER_COUNT', 'CONTAINER_COUNT', 'containerCount'], '');
  },
  get STORED_PRODUCT_COUNT() {
    return readEnv(['DELIVERY_ORDER_FIELDS.STORED_PRODUCT_COUNT', 'STORED_PRODUCT_COUNT', 'storedProductCount'], '');
  },
  get VOLUME() {
    return readEnv(['DELIVERY_ORDER_FIELDS.VOLUME', 'VOLUME', 'volume'], '');
  },
  get WEIGHT() {
    return readEnv(['DELIVERY_ORDER_FIELDS.WEIGHT', 'WEIGHT', 'weight'], '');
  }
};

// 配送站点相关字段 - 使用getter延迟读取
export const DELIVERY_SITE_FIELDS = {
  get NAME() {
    return readEnv(['DELIVERY_SITE_FIELDS.NAME', 'NAME', 'siteName'], '');
  },
  get SITE_INFO() {
    return readEnv(['DELIVERY_SITE_FIELDS.SITE_INFO', 'SITE_INFO', 'siteInfo'], '');
  },
  get ADDRESS() {
    return readEnv(['DELIVERY_SITE_FIELDS.ADDRESS', 'ADDRESS', 'address'], '');
  },
  get CONTACT_PERSON() {
    return readEnv(['DELIVERY_SITE_FIELDS.CONTACT_PERSON', 'CONTACT_PERSON', 'contactPerson'], '');
  },
  get CONTACT_PHONE() {
    return readEnv(['DELIVERY_SITE_FIELDS.CONTACT_PHONE', 'CONTACT_PHONE', 'contactPhone'], '');
  },
  get STATUS() {
    return readEnv(['DELIVERY_SITE_FIELDS.STATUS', 'STATUS', 'status'], '');
  },
  get TYPE() {
    return readEnv(['DELIVERY_SITE_FIELDS.TYPE', 'TYPE', 'type'], '');
  }
};

// 司机相关字段 - 使用getter延迟读取
export const DRIVER_FIELDS = {
  get NAME() {
    return readEnv(['DRIVER_FIELDS.NAME', 'NAME', 'driverName'], '');
  },
  get CONTACT() {
    return readEnv(['DRIVER_FIELDS.CONTACT', 'CONTACT', 'driverContact'], '');
  },
  get STATUS() {
    return readEnv(['DRIVER_FIELDS.STATUS', 'STATUS', 'driverStatus'], '');
  },
  get ID_NUMBER() {
    return readEnv(['DRIVER_FIELDS.ID_NUMBER', 'ID_NUMBER', 'idNumber'], '');
  },
  get LICENSE_NUMBER() {
    return readEnv(['DRIVER_FIELDS.LICENSE_NUMBER', 'LICENSE_NUMBER', 'licenseNumber'], '');
  }
};

// 车辆相关字段 - 使用getter延迟读取
export const VEHICLE_FIELDS = {
  get MODEL() {
    return readEnv(['VEHICLE_FIELDS.MODEL', 'MODEL', 'vehicleModel'], '');
  },
  get PLATE_NUMBER() {
    return readEnv(['VEHICLE_FIELDS.PLATE_NUMBER', 'PLATE_NUMBER', 'plateNumber'], '');
  },
  get STATUS() {
    return readEnv(['VEHICLE_FIELDS.STATUS', 'STATUS', 'vehicleStatus'], '');
  },
  get CAPACITY() {
    return readEnv(['VEHICLE_FIELDS.CAPACITY', 'CAPACITY', 'capacity'], '');
  },
  get TYPE() {
    return readEnv(['VEHICLE_FIELDS.TYPE', 'TYPE', 'vehicleType'], '');
  }
};

// 容器相关字段 - 使用getter延迟读取
export const CONTAINER_FIELDS = {
  get CODE() {
    return readEnv(['CONTAINER_FIELDS.CODE', 'CODE', 'containerCode'], '');
  },
  get CONTAINER_CODE() {
    return readEnv(['CONTAINER_FIELDS.CONTAINER_CODE', 'CONTAINER_CODE', 'containerCode'], '');
  },
  get TYPE() {
    return readEnv(['CONTAINER_FIELDS.TYPE', 'TYPE', 'containerType'], '');
  },
  get STATUS() {
    return readEnv(['CONTAINER_FIELDS.STATUS', 'containerstate', 'STATUS', 'containerStatus'], '');
  },
  get CAPACITY() {
    return readEnv(['CONTAINER_FIELDS.CAPACITY', 'CAPACITY', 'capacity'], '');
  },
  get CURRENT_WEIGHT() {
    return readEnv(['CONTAINER_FIELDS.CURRENT_WEIGHT', 'CURRENT_WEIGHT', 'currentWeight'], '');
  },
  get PRODUCTS() {
    return readEnv(['CONTAINER_FIELDS.PRODUCTS', 'PRODUCTS', 'products'], '');
  },
  get CONTAINER_SITE_INFO() {
    return readEnv(['CONTAINER_FIELDS.CONTAINER_SITE_INFO', 'CONTAINER_SITE_INFO', 'containerSiteInfo'], '');
  },
  get CREATED_AT() {
    return readEnv(['CONTAINER_FIELDS.CREATED_AT', 'CREATED_AT', 'createdAt'], '');
  },
  get UPDATED_AT() {
    return readEnv(['CONTAINER_FIELDS.UPDATED_AT', 'UPDATED_AT', 'updatedAt'], '');
  },
  get RELATION_FIELD() {
    return readEnv(['CONTAINER_FIELDS.RELATION_FIELD', 'RELATION_FIELD', 'relationField'], '');
  },
  get PRODUCT_NAME() {
    return readEnv(['CONTAINER_FIELDS.PRODUCT_NAME', 'PRODUCT_NAME', 'productName'], '');
  },
  get QUANTITY() {
    return readEnv(['CONTAINER_FIELDS.QUANTITY', 'QUANTITY', 'quantity'], '');
  }
};

// Webhook 配置（动态读取）
export const WEBHOOKS = {
  // 统一主 webhook（可作为默认）
  get DELIVERY_WEBHOOK_URL() {
    return readEnv(['webhookUrl', 'DELIVERY_WEBHOOK_URL'], '');
  },
  // 具体业务 webhook：新建/修改/确认（不同应用可不同）
  get CREATE() {
    const url = readEnv(['CREATE_WEBHOOK_URL', 'deliveryCreateWebhook', 'createWebhookUrl'], '');
    console.log('WEBHOOKS.CREATE 读取结果:', url);
    return url || WEBHOOKS.DELIVERY_WEBHOOK_URL;
  },
  get MODIFY() {
    return readEnv(['MODIFY_WEBHOOK_URL', 'deliveryModifyWebhook', 'modifyWebhookUrl'], WEBHOOKS.DELIVERY_WEBHOOK_URL);
  },
  get CONFIRM() {
    return readEnv(['CONFIRM_WEBHOOK_URL', 'deliveryConfirmWebhook', 'confirmWebhookUrl'], WEBHOOKS.DELIVERY_WEBHOOK_URL);
  }
};

// 分页配置
export const PAGINATION_CONFIG = {
  DEFAULT_PAGE_SIZE: 50,
  MAX_PAGE_SIZE: 200
};

// 配送状态枚举
export const DELIVERY_STATUS = {
  PENDING: 'pending',           // 待处理
  IN_PROGRESS: 'in_progress',   // 配送中
  SHIPPED: 'shipped',           // 已发运  
  COMPLETED: 'completed',       // 已完成
  CANCELLED: 'cancelled',       // 已取消
  FAILED: 'failed'             // 配送失败
};

// 配送方式枚举
export const DELIVERY_METHODS = {
  WAREHOUSE: '仓库配送',        // 仓库配送
  DIRECT: '直接配送'            // 直接配送
};

// 容器状态枚举
export const CONTAINER_STATUS = {
  AVAILABLE: 'available',       // 可用
  IN_USE: 'in_use',            // 使用中
  MAINTENANCE: 'maintenance',   // 维护中
  DAMAGED: 'damaged'           // 损坏
};

// 字段映射工具函数 - 支持两种数据格式
export const getFieldValue = (data, fieldId, defaultValue = '') => {
  if (!data || !fieldId) {
    return defaultValue;
  }
  
  // 明道云格式：数据直接作为对象属性
  if (typeof data === 'object' && !Array.isArray(data)) {
    return data[fieldId] || defaultValue;
  }
  
  // 旧格式：controls数组格式（兼容处理）
  if (Array.isArray(data)) {
    const field = data.find(control => control.controlId === fieldId);
    return field ? (field.value || defaultValue) : defaultValue;
  }
  
  return defaultValue;
};

// 根据字段名称获取值（备用方案）
export const getFieldValueByName = (data, fieldName, defaultValue = '') => {
  if (!data || !fieldName) {
    return defaultValue;
  }
  
  // 明道云格式：暂不支持按名称查找（因为明道云直接返回字段ID作为key）
  if (typeof data === 'object' && !Array.isArray(data)) {
    // 可能需要遍历寻找，但这里先返回默认值
    return defaultValue;
  }
  
  // 旧格式：controls数组格式
  if (Array.isArray(data)) {
    const field = data.find(control => control.controlName === fieldName);
    return field ? (field.value || defaultValue) : defaultValue;
  }
  
  return defaultValue;
};

// 智能字段值获取（尝试多种方式）
export const getFieldValueSmart = (data, fieldId, fieldNames = [], defaultValue = '') => {
  // 首先尝试通过字段ID获取
  let value = getFieldValue(data, fieldId, null);
  if (value !== null && value !== '') {
    return value;
  }
  
  // 然后尝试通过字段名称获取
  for (const fieldName of fieldNames) {
    value = getFieldValueByName(data, fieldName, null);
    if (value !== null && value !== '') {
      return value;
    }
  }
  
  return defaultValue;
};

// 配送单数据转换函数
export const transformDeliveryOrderData = (rows) => {
  if (!rows || !Array.isArray(rows)) {
    console.warn('transformDeliveryOrderData: rows is not an array:', typeof rows, rows);
    return [];
  }
  
  
  return rows.map((row, index) => {
    // 获取配送方式
    const deliveryMethod = getFieldValueSmart(
      row,
      DELIVERY_ORDER_FIELDS.METHOD,
      ['配送方式', '配送类型', 'delivery_method', 'method'],
      '未知配送方式'
    );
    
    // 获取目的地
    const destination = getFieldValueSmart(
      row,
      DELIVERY_ORDER_FIELDS.DESTINATION,
      ['发运目的地', '目的地', '配送地址', 'destination', 'address'],
      ''
    );
    
    // 获取司机信息
    const driver = getFieldValueSmart(
      row,
      DELIVERY_ORDER_FIELDS.DRIVER,
      ['司机', '驾驶员', 'driver'],
      ''
    );
    
    // 获取车辆信息
    const vehicle = getFieldValueSmart(
      row,
      DELIVERY_ORDER_FIELDS.VEHICLE,
      ['车辆', '配送车辆', 'vehicle'],
      ''
    );
    
    // 获取备注
    const remarks = getFieldValueSmart(
      row,
      DELIVERY_ORDER_FIELDS.REMARKS,
      ['备注', '说明', 'remarks', 'notes'],
      ''
    );
    
    // 获取状态
    const rawStatus = getFieldValueSmart(
      row,
      DELIVERY_ORDER_FIELDS.STATUS,
      ['状态', 'status'],
      ''
    );
    
    // 状态映射和标准化
    let status;
    if (rawStatus) {
      const statusStr = String(rawStatus).toLowerCase();
      if (statusStr.includes('完成') || statusStr.includes('completed') || statusStr === '已完成') {
        status = DELIVERY_STATUS.COMPLETED;
      } else if (statusStr.includes('进行') || statusStr.includes('progress') || statusStr === '配送中') {
        status = DELIVERY_STATUS.IN_PROGRESS;
      } else if (statusStr.includes('取消') || statusStr.includes('cancelled') || statusStr === '已取消') {
        status = DELIVERY_STATUS.CANCELLED;
      } else if (statusStr.includes('失败') || statusStr.includes('failed') || statusStr === '配送失败') {
        status = DELIVERY_STATUS.FAILED;
      } else {
        status = DELIVERY_STATUS.PENDING;
      }
    } else {
      status = DELIVERY_STATUS.PENDING;
    }
    
    // 获取时间信息
    const createdAt = getFieldValueSmart(
      row,
      DELIVERY_ORDER_FIELDS.CREATED_AT,
      ['创建时间', '下单时间', 'created_at', 'create_time'],
      new Date().toISOString()
    );
    
    const result = {
      id: row.rowid || '',
      deliveryMethod: deliveryMethod,
      destination: destination,
      driver: driver,
      vehicle: vehicle,
      remarks: remarks,
      status: status,
      createdAt: createdAt,
      rawData: row
    };
    
    // 仅在需要调试时输出第一条记录
    if (index === 0) {
      // Debug info for first record
    }
    
    return result;
  }).filter(item => item !== null);
};

// 配送站点数据转换函数
export const transformDeliverySiteData = (rows) => {
  if (!rows || !Array.isArray(rows)) {
    console.warn('transformDeliverySiteData: rows is not an array:', typeof rows, rows);
    return [];
  }
  
  
  return rows.map((row, index) => {
    // 获取站点名称
    const siteName = getFieldValueSmart(
      row,
      DELIVERY_SITE_FIELDS.NAME,
      ['站点名称', '配送站点', '网点名称', 'site_name', 'name'],
      '未知站点'
    );
    
    // 获取站点地址
    const address = getFieldValueSmart(
      row,
      DELIVERY_SITE_FIELDS.ADDRESS,
      ['站点地址', '地址', 'address'],
      ''
    );
    
    // 获取联系信息
    const contactPerson = getFieldValueSmart(
      row,
      DELIVERY_SITE_FIELDS.CONTACT_PERSON,
      ['联系人', '负责人', 'contact_person'],
      ''
    );
    
    const contactPhone = getFieldValueSmart(
      row,
      DELIVERY_SITE_FIELDS.CONTACT_PHONE,
      ['联系电话', '站点电话', 'contact_phone', 'phone'],
      ''
    );
    
    const result = {
      id: row.rowid || '',
      name: siteName,
      address: address,
      contactPerson: contactPerson,
      contactPhone: contactPhone,
      rawData: row
    };
    
    return result;
  }).filter(item => item !== null);
};

// 司机数据转换函数
export const transformDriverData = (rows) => {
  if (!rows || !Array.isArray(rows)) {
    console.warn('transformDriverData: rows is not an array:', typeof rows, rows);
    return [];
  }
  
  
  return rows.map((row, index) => {
    // 获取司机姓名
    const driverName = getFieldValueSmart(
      row,
      DRIVER_FIELDS.NAME,
      ['司机姓名', '姓名', '驾驶员姓名', 'driver_name', 'name'],
      '未知司机'
    );
    
    // 获取司机联系方式
    const contact = getFieldValueSmart(
      row,
      DRIVER_FIELDS.CONTACT,
      ['司机联系方式', '联系方式', '手机号', 'contact', 'phone'],
      ''
    );
    
    const result = {
      id: row.rowid || '',
      name: driverName,
      contact: contact,
      rawData: row
    };
    
    return result;
  }).filter(item => item !== null);
};

// 车辆数据转换函数
export const transformVehicleData = (rows) => {
  if (!rows || !Array.isArray(rows)) {
    console.warn('transformVehicleData: rows is not an array:', typeof rows, rows);
    return [];
  }
  
  
  return rows.map((row, index) => {
    // 获取车型
    const vehicleModel = getFieldValueSmart(
      row,
      VEHICLE_FIELDS.MODEL,
      ['车型', '车辆型号', 'vehicle_model', 'model'],
      '未知车型'
    );
    
    // 获取车牌号
    const plateNumber = getFieldValueSmart(
      row,
      VEHICLE_FIELDS.PLATE_NUMBER,
      ['车牌号', '车牌', '车辆号', 'plate_number', 'plate'],
      ''
    );
    
    const result = {
      id: row.rowid || '',
      model: vehicleModel,
      plateNumber: plateNumber,
      displayText: plateNumber ? `${vehicleModel} (${plateNumber})` : vehicleModel,
      rawData: row
    };
    
    return result;
  }).filter(item => item !== null);
};

// 容器数据转换函数
export const transformContainerData = (rows) => {
  if (!rows || !Array.isArray(rows)) {
    console.warn('transformContainerData: rows is not an array:', typeof rows, rows);
    return [];
  }
  
  
  return rows.map((row, index) => {
    // 获取容器编号
    const containerCode = getFieldValueSmart(
      row,
      CONTAINER_FIELDS.CODE,
      ['容器编号', '容器号', '编号', 'container_code', 'code'],
      row.rowid || '未知编号'
    );
    
    // 获取商品信息
    const products = getFieldValueSmart(
      row,
      CONTAINER_FIELDS.PRODUCTS,
      ['商品信息', '货品信息', 'products', 'goods'],
      ''
    );
    
    // 获取容器类型
    const containerType = getFieldValueSmart(
      row,
      CONTAINER_FIELDS.TYPE,
      ['容器类型', '类型', 'container_type', 'type'],
      ''
    );
    
    // 获取容器状态
    const rawStatus = getFieldValueSmart(
      row,
      CONTAINER_FIELDS.STATUS,
      ['容器状态', '状态', 'status'],
      ''
    );
    
    // 状态映射
    let status;
    if (rawStatus) {
      const statusStr = String(rawStatus).toLowerCase();
      if (statusStr.includes('使用') || statusStr.includes('in_use')) {
        status = CONTAINER_STATUS.IN_USE;
      } else if (statusStr.includes('维护') || statusStr.includes('maintenance')) {
        status = CONTAINER_STATUS.MAINTENANCE;
      } else if (statusStr.includes('损坏') || statusStr.includes('damaged')) {
        status = CONTAINER_STATUS.DAMAGED;
      } else {
        status = CONTAINER_STATUS.AVAILABLE;
      }
    } else {
      status = CONTAINER_STATUS.AVAILABLE;
    }
    
    const result = {
      id: row.rowid || '',
      code: containerCode,
      type: containerType,
      status: status,
      products: products,
      rawData: row
    };
    
    return result;
  }).filter(item => item !== null);
};

// 数据类型常量（明道云API规范）
export const DATA_TYPES = {
  TEXT: 2,        // 文本
  NUMBER: 6,      // 数字
  DATE: 15,       // 日期
  DATETIME: 16,   // 日期时间
  ATTACHMENT: 14, // 附件
  OPTIONS: 11     // 选项
};

// 过滤条件类型（明道云API规范）
export const FILTER_TYPES = {
  EQUAL: 1,       // 等于
  CONTAINS: 2,    // 包含
  NOT_EQUAL: 3,   // 不等于
  GREATER: 4,     // 大于
  LESS: 5,        // 小于
  IS_EMPTY: 6,    // 为空
  IS_NOT_EMPTY: 7 // 不为空
};

// 配置验证函数
export const validateConfig = () => {
  const errors = [];
  
  // 检查工作表ID
  if (!WORKSHEET_IDS.DELIVERY_ORDERS) {
    errors.push('缺少配送单工作表ID');
  }
  
  if (!WORKSHEET_IDS.DELIVERY_SITES) {
    errors.push('缺少配送站点工作表ID');
  }
  
  if (!WORKSHEET_IDS.CONTAINERS) {
    errors.push('缺少容器工作表ID');
  }
  
  // 检查关键字段ID
  if (!DELIVERY_ORDER_FIELDS.METHOD) {
    errors.push('缺少配送方式字段ID');
  }
  
  if (!DELIVERY_SITE_FIELDS.NAME) {
    errors.push('缺少站点名称字段ID');
  }
  
  if (!DRIVER_FIELDS.NAME) {
    errors.push('缺少司机姓名字段ID');
  }
  
  if (!DRIVER_FIELDS.CONTACT) {
    errors.push('缺少司机联系方式字段ID');
  }
  
  if (!VEHICLE_FIELDS.MODEL) {
    errors.push('缺少车型字段ID');
  }
  
  if (!CONTAINER_FIELDS.PRODUCTS) {
    errors.push('缺少容器商品信息字段ID');
  }
  
  return {
    isValid: errors.length === 0,
    errors
  };
};

// 统一配置对象 - 使用getter延迟读取，支持运行时参数化
export const CONFIG = {
  // API配置
  get api() {
    return API_CONFIG;
  },
  
  // 工作表ID
  get worksheetIds() {
    return {
      delivery: WORKSHEET_IDS.DELIVERY_ORDERS,
      sites: WORKSHEET_IDS.DELIVERY_SITES,
      containers: WORKSHEET_IDS.CONTAINERS,
      containerManagement: WORKSHEET_IDS.CONTAINER_MANAGEMENT,
      drivers: WORKSHEET_IDS.DRIVERS,
      vehicles: WORKSHEET_IDS.VEHICLES
    };
  },
  
  // 视图ID
  get viewIds() {
    return {
      delivery: VIEW_IDS.DELIVERY_ORDERS_DEFAULT,
      sites: VIEW_IDS.DELIVERY_SITES_DEFAULT,
      containers: VIEW_IDS.CONTAINERS_DEFAULT
    };
  },
  
  // 字段配置
  get fields() {
    return {
      // 配送单字段
      orderNumber: DELIVERY_ORDER_FIELDS.ORDER_NUMBER,
      deliveryMethod: DELIVERY_ORDER_FIELDS.METHOD,
      destination: DELIVERY_ORDER_FIELDS.DESTINATION,
      driver: DELIVERY_ORDER_FIELDS.DRIVER,
      vehicle: DELIVERY_ORDER_FIELDS.VEHICLE,
      container: DELIVERY_ORDER_FIELDS.CONTAINER,
      ownedContainers: DELIVERY_ORDER_FIELDS.CONTAINER_CODES,
      remarks: DELIVERY_ORDER_FIELDS.REMARKS,
      status: DELIVERY_ORDER_FIELDS.STATUS,
      createdAt: DELIVERY_ORDER_FIELDS.CREATED_AT,
      updatedAt: DELIVERY_ORDER_FIELDS.UPDATED_AT,
      expectedDeliveryTime: DELIVERY_ORDER_FIELDS.EXPECTED_DELIVERY_TIME,
      actualDeliveryTime: DELIVERY_ORDER_FIELDS.ACTUAL_DELIVERY_TIME,
      phoneNumber: DELIVERY_ORDER_FIELDS.PHONE_NUMBER,
      containerCount: DELIVERY_ORDER_FIELDS.CONTAINER_COUNT,
      storedProductCount: DELIVERY_ORDER_FIELDS.STORED_PRODUCT_COUNT,
      volume: DELIVERY_ORDER_FIELDS.VOLUME,
      weight: DELIVERY_ORDER_FIELDS.WEIGHT,
      
      // 配送站点字段
      siteName: DELIVERY_SITE_FIELDS.NAME,
      siteInfo: DELIVERY_SITE_FIELDS.SITE_INFO,
      siteAddress: DELIVERY_SITE_FIELDS.ADDRESS,
      siteContactPerson: DELIVERY_SITE_FIELDS.CONTACT_PERSON,
      siteContactPhone: DELIVERY_SITE_FIELDS.CONTACT_PHONE,
      siteStatus: DELIVERY_SITE_FIELDS.STATUS,
      siteType: DELIVERY_SITE_FIELDS.TYPE,
      
      // 司机字段
      driverName: DRIVER_FIELDS.NAME,
      driverContact: DRIVER_FIELDS.CONTACT,
      driverStatus: DRIVER_FIELDS.STATUS,
      driverIdNumber: DRIVER_FIELDS.ID_NUMBER,
      driverLicenseNumber: DRIVER_FIELDS.LICENSE_NUMBER,
      
      // 车辆字段
      vehicleModel: VEHICLE_FIELDS.MODEL,
      vehiclePlateNumber: VEHICLE_FIELDS.PLATE_NUMBER,
      vehicleStatus: VEHICLE_FIELDS.STATUS,
      vehicleCapacity: VEHICLE_FIELDS.CAPACITY,
      vehicleType: VEHICLE_FIELDS.TYPE,
      
      // 容器字段
      containerCode: CONTAINER_FIELDS.CONTAINER_CODE,
      containerType: CONTAINER_FIELDS.TYPE,
      containerStatus: CONTAINER_FIELDS.STATUS,
      containerCapacity: CONTAINER_FIELDS.CAPACITY,
      containerCurrentWeight: CONTAINER_FIELDS.CURRENT_WEIGHT,
      containerProducts: CONTAINER_FIELDS.PRODUCTS,
      containerSiteInfo: CONTAINER_FIELDS.CONTAINER_SITE_INFO,
      containerCreatedAt: CONTAINER_FIELDS.CREATED_AT,
      containerUpdatedAt: CONTAINER_FIELDS.UPDATED_AT,
      containerRelationField: CONTAINER_FIELDS.RELATION_FIELD,
      
      // 兼容性字段映射
      driverTableName: DRIVER_FIELDS.NAME,
      driverTableContact: DRIVER_FIELDS.CONTACT,
      vehicleTableModel: VEHICLE_FIELDS.MODEL,
      vehicleTablePlateNumber: VEHICLE_FIELDS.PLATE_NUMBER
    };
  }
};

// 导出所有配置
export default {
  WORKSHEET_IDS,
  VIEW_IDS,
  API_CONFIG,
  DELIVERY_ORDER_FIELDS,
  DELIVERY_SITE_FIELDS,
  DRIVER_FIELDS,
  VEHICLE_FIELDS,
  CONTAINER_FIELDS,
  PAGINATION_CONFIG,
  DELIVERY_STATUS,
  DELIVERY_METHODS,
  CONTAINER_STATUS,
  getFieldValue,
  getFieldValueByName,
  getFieldValueSmart,
  transformDeliveryOrderData,
  transformDeliverySiteData,
  transformDriverData,
  transformVehicleData,
  transformContainerData,
  validateConfig,
  DATA_TYPES,
  FILTER_TYPES,
  CONFIG,
  readEnv,
  getConfigSnapshot
};

// 补充命名导出，确保按需导入时可用
export { readEnv, getConfigSnapshot };